package com.huffman.smart_picture.controller;

import cn.hutool.core.util.StrUtil;
import com.huffman.smart_picture.api.search.ImageSearchApiFacade;
import com.huffman.smart_picture.api.search.ImageSearchResult;
import com.huffman.smart_picture.common.auth.AuthConstant;
import com.huffman.smart_picture.common.auth.SessionContext;
import com.huffman.smart_picture.common.auth.annotation.CheckRole;
import com.huffman.smart_picture.common.auth.annotation.LoginRequired;
import com.huffman.smart_picture.common.UserSession;
import com.huffman.smart_picture.common.base.reponse.PageQueryResult;
import com.huffman.smart_picture.common.base.reponse.ResponseResult;
import com.huffman.smart_picture.common.exception.ErrorEnum;
import com.huffman.smart_picture.domain.constants.CommonConstant;
import com.huffman.smart_picture.domain.constants.PictureConstant;
import com.huffman.smart_picture.domain.entity.Picture;
import com.huffman.smart_picture.domain.request.picture.*;
import com.huffman.smart_picture.domain.vo.pircture.*;
import com.huffman.smart_picture.service.PictureService;
import com.huffman.smart_picture.utils.ColorUtil;
import com.huffman.smart_picture.utils.ResponseUtil;
import com.huffman.smart_picture.utils.ThrowUtil;
import io.swagger.annotations.ApiOperation;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/picture")
public class PictureController {

    @Resource
    private SessionContext sessionContext;

    @Resource
    private PictureService pictureService;

    @PostMapping("/upload")
    @ApiOperation(value = "上传图片")
    @LoginRequired
    public ResponseResult<PictureVo> uploadPicture(@RequestPart("file") MultipartFile multipartFile, PictureUploadRequest pictureUploadRequest) {
        UserSession userSession = sessionContext.getUserSession();
        PictureVo pictureVo = pictureService.uploadPicture(multipartFile, pictureUploadRequest, userSession);
        pictureVo.setUser(userSession);
        return ResponseUtil.success(pictureVo);
    }

    @PostMapping("/upload/url")
    @ApiOperation(value = "url图片上传")
    @LoginRequired
    public ResponseResult<PictureVo> uploadPictureByUrl(@RequestBody PictureUploadRequest pictureUploadRequest) {
        UserSession userSession = sessionContext.getUserSession();
        String pictureUrl = pictureUploadRequest.getUrl();
        PictureVo pictureVo = pictureService.uploadPicture(pictureUrl, pictureUploadRequest, userSession);
        pictureVo.setUser(userSession);
        return ResponseUtil.success(pictureVo);
    }

    @PostMapping("/upload/batch")
    @ApiOperation(value = "管理员批量导入图片")
    @CheckRole(roles = CommonConstant.ADMIN)
    public ResponseResult<PictureVo> uploadPictureByBatch(@RequestBody PictureUploadByBatchRequest pictureUploadByBatchRequest) {
        UserSession userSession = sessionContext.getUserSession();
        ThrowUtil.throwIf(pictureUploadByBatchRequest == null, ErrorEnum.PARAM_EMPTY, "请求参数为空");
        String category = pictureUploadByBatchRequest.getCategory();
        ThrowUtil.throwIf(!StringUtils.hasText(category), ErrorEnum.PARAM_EMPTY, "图片分类为空");
        Integer uploadCount = pictureService.uploadPictureByBatch(pictureUploadByBatchRequest, userSession);
        return ResponseUtil.success(uploadCount);
    }


    @GetMapping("/search/{id}")
    @ApiOperation(value = "查询图片信息")
    @CheckRole(roles = {CommonConstant.ADMIN})
    public ResponseResult<Picture> searchPicture(@PathVariable("id") Long id) {
        ThrowUtil.throwIf(id <= 0, ErrorEnum.PARAM_CHECK_MISTAKE, "参数错误");
        Picture picture = pictureService.getById(id);
        ThrowUtil.throwIf(picture == null, ErrorEnum.RESOURCE_NOT_FIND, "图片不存在");
        return ResponseUtil.success(picture);
    }

    @GetMapping("/search/detail/{id}")
    @ApiOperation(value = "查询图片信息")
    public ResponseResult<PictureVo> searchPictureDetailVo(@PathVariable("id") Long id, HttpServletRequest httpServletRequest) {
        ThrowUtil.throwIf(id <= 0, ErrorEnum.PARAM_CHECK_MISTAKE, "参数错误");
        UserSession userSession = (UserSession) httpServletRequest.getSession().getAttribute(AuthConstant.LOGIN_USER);
        PictureDetailVo pictureDetailVo = pictureService.getPictureDetail(id, userSession);
        return ResponseUtil.success(pictureDetailVo);
    }


    @PostMapping("/delete/{id}")
    @ApiOperation(value = "删除图片")
    @LoginRequired
    public ResponseResult<Boolean> deletePicture(@PathVariable("id") Long id) {
        ThrowUtil.throwIf(id <= 0, ErrorEnum.PARAM_CHECK_MISTAKE, "参数错误");
        UserSession userSession = sessionContext.getUserSession();
        boolean res = pictureService.deletePicture(id, userSession);
        return ResponseUtil.success(res);
    }


    @PostMapping("/update")
    @ApiOperation(value = "更新图片")
    @LoginRequired
    public ResponseResult updatePicture(@RequestBody PictureUpdateRequest pictureUpdateRequest) {
        //校验参数是否合法
        ThrowUtil.throwIf(pictureUpdateRequest == null, ErrorEnum.PARAM_EMPTY, "参数为空");
        Long id = pictureUpdateRequest.getId();
        ThrowUtil.throwIf(id == null || id <= 0, ErrorEnum.PARAM_ILLICIT, "图片id非法");
        String introduction = pictureUpdateRequest.getIntroduction();
        String picName = pictureUpdateRequest.getName();
        if (StringUtils.hasText(introduction)) {
            ThrowUtil.throwIf(introduction.length() > 1024, ErrorEnum.PARAM_ILLICIT, "简介过长");
        }
        if (StringUtils.hasText(picName)) {
            ThrowUtil.throwIf(picName.length() > 128, ErrorEnum.PARAM_ILLICIT, "图片名称过长");
        }

        UserSession userSession = sessionContext.getUserSession();
        pictureService.saveOrUpdatePicture(pictureUpdateRequest, userSession);
        return ResponseUtil.success();
    }

    @PostMapping("/update/batch")
    @ApiOperation(value = "批量更新个人空间图片")
    @LoginRequired
    public ResponseResult updatePictureByBatch(@RequestBody PictureUpdateByBatchRequest pictureUpdateByBatchRequest) {
        return ResponseUtil.success();
    }

    @PostMapping("/page")
    @ApiOperation(value = "分页查询")
    @CheckRole(roles = {CommonConstant.ADMIN})
    public ResponseResult pageQuery(@RequestBody PicturePageQueryRequest picturePageQueryRequest) {
        ThrowUtil.throwIf(picturePageQueryRequest == null, ErrorEnum.PARAM_EMPTY, "查询参数为空");
        PageQueryResult<PictureViewVo> pageQueryResult = pictureService.pageQueryByAdmin(picturePageQueryRequest);
        return ResponseUtil.success(pageQueryResult);
    }

    @PostMapping("/page/waterfall")
    @ApiOperation(value = "分页查询")
    public ResponseResult<PageQueryResult<WaterfallPictureVo>> pageQueryByUser(@RequestBody PicturePageQueryRequest picturePageQueryRequest, HttpServletRequest httpServletRequest) {
        ThrowUtil.throwIf(picturePageQueryRequest == null, ErrorEnum.PARAM_EMPTY, "查询参数为空");
        Integer pageSize = picturePageQueryRequest.getPageSize();
        ThrowUtil.throwIf(pageSize > 20, ErrorEnum.PARAM_ILLICIT, "请求参数错误");
        UserSession userSession = (UserSession) httpServletRequest.getSession().getAttribute(AuthConstant.LOGIN_USER);
        PageQueryResult<WaterfallPictureVo> pageQueryResult = pictureService.pageQueryWaterfall(picturePageQueryRequest, userSession);
        return ResponseUtil.success(pageQueryResult);
    }

    @PostMapping("/page/space/vo")
    @ApiOperation(value = "分页查询")
    @LoginRequired
    public ResponseResult pageQuerySpacePicture(@RequestBody PicturePageQueryRequest picturePageQueryRequest) {
        ThrowUtil.throwIf(picturePageQueryRequest == null, ErrorEnum.PARAM_EMPTY, "查询参数为空");
        Integer pageNum = picturePageQueryRequest.getPageNum();
        ThrowUtil.throwIf(pageNum < 1, ErrorEnum.PARAM_ILLICIT, "请求参数非法");
        Integer pageSize = picturePageQueryRequest.getPageSize();
        ThrowUtil.throwIf(pageSize > 20, ErrorEnum.PARAM_ILLICIT, "请求参数错误");
        UserSession userSession = sessionContext.getUserSession();
        PageQueryResult<Picture> pageQueryResult = pictureService.pageQuerySpacePicture(picturePageQueryRequest, userSession);
        return ResponseUtil.success(pageQueryResult);
    }

    @PostMapping("/review")
    @ApiOperation(value = "图片审核")
    @CheckRole(roles = {CommonConstant.ADMIN})
    public ResponseResult<Boolean> reviewPicture(@RequestBody PictureReviewRequest pictureReviewRequest) {
        ThrowUtil.throwIf(pictureReviewRequest == null, ErrorEnum.PARAM_EMPTY, "审核参数为空");
        Long id = pictureReviewRequest.getId();
        ThrowUtil.throwIf(Objects.isNull(id) || id < 1, ErrorEnum.PARAM_ILLICIT, "图片id非法或为空");
        UserSession userSession = sessionContext.getUserSession();
        pictureService.doPictureReview(pictureReviewRequest, userSession);
        return ResponseUtil.success(true);
    }

    @PostMapping("/search/picture")
    @ApiOperation(value = "以图搜图")
    public ResponseResult searchByPicture(@RequestBody PictureSearchByPictureRequest pictureSearchByPictureRequest) {
        ThrowUtil.throwIf(pictureSearchByPictureRequest == null, ErrorEnum.PARAM_EMPTY, "请求参数为空");
        Long pictureId = pictureSearchByPictureRequest.getPictureId();
        ThrowUtil.throwIf(Objects.isNull(pictureId) || pictureId < 1, ErrorEnum.PARAM_ILLICIT, "图片id非法或为空");
        Picture picture = pictureService.getById(pictureId);
        ThrowUtil.throwIf(picture == null, ErrorEnum.CHECK_INFO_EXPIRED, "图片不存在");
        List<ImageSearchResult> images = ImageSearchApiFacade.searchImage(picture.getUrl());
        return ResponseUtil.success(images);
    }

    @PostMapping("/search/color")
    @ApiOperation(value = "颜色搜图-个人空间")
    @LoginRequired
    public ResponseResult searchByColor(@RequestBody PictureSearchByColorRequest pictureSearchByColorRequest) {
        ThrowUtil.throwIf(pictureSearchByColorRequest == null, ErrorEnum.PARAM_EMPTY, "请求参数为空");
        Long spaceId = pictureSearchByColorRequest.getSpaceId();
        String picColor = pictureSearchByColorRequest.getPicColor();
        ThrowUtil.throwIf(spaceId < 1, ErrorEnum.PARAM_ILLICIT, "空间id非法");
        ThrowUtil.throwIf(!StringUtils.hasText(picColor), ErrorEnum.PARAM_ILLICIT, "目标颜色非法");
        UserSession userSession = sessionContext.getUserSession();
        List<PictureVo> pictureVoList = pictureService.searchByColor(spaceId, picColor, userSession);
        return ResponseUtil.success(pictureVoList);
    }

    @GetMapping("/tag_category")
    public ResponseResult<PictureTagCategoryVo> listPictureTagCategory() {
        PictureTagCategoryVo pictureTagCategory = new PictureTagCategoryVo();
        pictureTagCategory.setTagList(PictureConstant.TAGS);
        pictureTagCategory.setCategoryList(PictureConstant.CATEGORY);
        return ResponseUtil.success(pictureTagCategory);
    }

    @PostMapping("/idphoto")
    @ApiOperation(value = "证件照制作(透明底)")
    @LoginRequired
    public ResponseResult produceIdPhoto(@RequestPart("file") MultipartFile multipartFile,
                                         PictureProcessRequest pictureProcessRequest,
                                         HttpServletRequest httpServletRequest
                                         ) {
        UserSession userSession = (UserSession) httpServletRequest.getSession().getAttribute(AuthConstant.LOGIN_USER);
        PictureProcessVo pictureProcessVo = pictureService.produceIdPhoto(multipartFile,pictureProcessRequest,userSession);
        return ResponseUtil.success(pictureProcessVo);
    }

    @PostMapping("/idphoto/download")
    @ApiOperation(value = "下载证件照")
    @LoginRequired
    public ResponseResult downloadIdPhoto(@RequestBody PictureProcessDownloadRequest pictureProcessDownloadRequest,
                                          HttpServletRequest httpServletRequest) {
        UserSession userSession = (UserSession) httpServletRequest.getSession().getAttribute(AuthConstant.LOGIN_USER);
        String color = pictureProcessDownloadRequest.getColor();
        String inputImageBase64 = pictureProcessDownloadRequest.getInputImageBase64();
        ThrowUtil.throwIf(StrUtil.isBlank(color),ErrorEnum.PARAM_EMPTY,"背景颜色为空");
        ThrowUtil.throwIf(!ColorUtil.isValidHexColor(color),ErrorEnum.PARAM_ILLICIT,"背景颜色非法");
        ThrowUtil.throwIf(StrUtil.isBlank(inputImageBase64),ErrorEnum.PARAM_EMPTY,"图片为空");
        PictureProcessDownloadVo pictureProcessDownloadVo = pictureService.downloadIdPhoto(color,inputImageBase64,userSession);
        return ResponseUtil.success(pictureProcessDownloadVo);
    }


}
